﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using Chaotic.Core.Extension;
using Chaotic.Core.Mvvm;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.FieldList;
using Telerik.Windows.Documents.Layout;
using Telerik.Windows.Documents.Model;
using Telerik.Windows.Documents.Model.Styles;
using DelegateCommand = Prism.Commands.DelegateCommand;

namespace Chaotic.Module.General.ViewModels
{
    public class LogContentViewModel
    {
        RadRichTextBox _richTextBox;
        RadDocumentEditor _documentEditor;


        public LogContentViewModel(IEventAggregator eventAggregator)
        {
            eventAggregator.ResgiterLogMessage((logMessage) =>
            {
                ClearTextNextLength(10000);

                ApplicationExtension.InvokeOnUIThread(() =>
                {
                    if (logMessage.IsError)
                    {
                        FocusTabActive?.Invoke();
                        WriteError(logMessage.Message);
                    }
                    else
                    {
                        WriteInfo(logMessage.Message);
                    }
                }); 
            });
        }

        public DelegateCommand ClearCommand => new DelegateCommand(Clear);


        private void Clear()
        {
            RichTextBox.Document = CreateDocument();
        }

        //激活窗口
        public Action FocusTabActive { get; set; }

        public RadRichTextBox RichTextBox
        {
            get { return _richTextBox; }
            set
            {
                if (value != _richTextBox)
                {
                    _richTextBox = value;
                    _richTextBox.Document = CreateDocument();
                }
            }
        }
 
       
        private void WriteError(string msg)
        {
            _documentEditor.ChangeStyleName("Error");
            _documentEditor.ChangeParagraphListStyle(null);
            _documentEditor.Insert(string.Format("{0}:  {1}", DateTime.Now.ToString("HH:mm:ss"), msg));
            _documentEditor.InsertParagraph();
        }

        private void WriteInfo(string msg)
        {
            _documentEditor.ChangeStyleName("Info");
            _documentEditor.ChangeParagraphListStyle(null);
            _documentEditor.Insert(string.Format("{0}:  {1}", DateTime.Now.ToString("HH:mm:ss"), msg));
            _documentEditor.InsertParagraph();
        }
 
        private RadDocument CreateDocument()
        {
            RadDocument document = new RadDocument();
            document.History.IsEnabled = false;

            _documentEditor = new RadDocumentEditor(document);
            _documentEditor.Document.LayoutMode = DocumentLayoutMode.Flow;

            StyleDefinition errorStyle = new StyleDefinition("Error", StyleType.Paragraph);
            errorStyle.ParagraphProperties.TextAlignment = RadTextAlignment.Left;
            errorStyle.ParagraphProperties.LineSpacing = 1;
            errorStyle.ParagraphProperties.LineSpacingType = LineSpacingType.AtLeast;
            errorStyle.ParagraphProperties.SpacingAfter = 0;
            errorStyle.ParagraphProperties.SpacingBefore = 0;
            errorStyle.ParagraphProperties.SuppressLineNumbers = true;
            errorStyle.SpanProperties.ForeColor = Colors.Red;
            errorStyle.NextStyleName = RadDocumentDefaultStyles.NormalStyleName;

            _documentEditor.Document.StyleRepository.Add(errorStyle);

            StyleDefinition infoStyle = new StyleDefinition("Info", StyleType.Paragraph);
            infoStyle.ParagraphProperties.TextAlignment = RadTextAlignment.Left;
            infoStyle.ParagraphProperties.LineSpacing = 1; 
            infoStyle.ParagraphProperties.LineSpacingType = LineSpacingType.AtLeast;
            infoStyle.ParagraphProperties.SpacingAfter = 0;
            infoStyle.ParagraphProperties.SpacingBefore = 0;
            infoStyle.ParagraphProperties.SuppressLineNumbers = true;
            infoStyle.SpanProperties.ForeColor = Colors.Black;
            infoStyle.NextStyleName = RadDocumentDefaultStyles.NormalStyleName; 
            _documentEditor.Document.StyleRepository.Add(infoStyle);


            return document;
        }

        private void ClearTextNextLength(int length)
        {
            if(RichTextBox == null || RichTextBox.Document == null)
            {
                return;
            }
            int textLengthWithLineBreaks = 0;
            foreach (var paragraph in RichTextBox.Document.EnumerateChildrenOfType<Telerik.Windows.Documents.Model.Paragraph>())
            {
                foreach (var span in paragraph.EnumerateChildrenOfType<Telerik.Windows.Documents.Model.Span>())
                {
                    textLengthWithLineBreaks += span.Text.Length;
                }
            }

            if (textLengthWithLineBreaks > length)
            {
                Clear();
            }
        }
    }
}
